// 3D Background using Three.js

let scene, camera, renderer;
let particles;
let mouseX = 0;
let mouseY = 0;
let windowHalfX = window.innerWidth / 2;
let windowHalfY = window.innerHeight / 2;

// Wait for load to ensure container exists
if (document.readyState === 'complete') {
    init();
    animate();
} else {
    window.addEventListener('load', () => {
        init();
        animate();
    });
}

function init() {
    // Canvas container
    const container = document.getElementById('canvas-container');
    if (!container) {
        console.error("Canvas container not found!");
        return;
    }

    // Camera
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
    camera.position.z = 1000;

    // Scene
    scene = new THREE.Scene();
    // Add some fog for depth
    scene.fog = new THREE.FogExp2(0x000000, 0.0007);

    // Particles
    const geometry = new THREE.BufferGeometry();
    const particleCount = 1000; // Number of particles

    const positions = [];
    const colors = [];

    const color = new THREE.Color();

    for (let i = 0; i < particleCount; i++) {
        const x = (Math.random() * 2 - 1) * 2000;
        const y = (Math.random() * 2 - 1) * 2000;
        const z = (Math.random() * 2 - 1) * 2000;

        positions.push(x, y, z);

        // Color variation based on theme (defaulting to blueish for now)
        color.setHSL(0.6, 1.0, 0.5 + Math.random() * 0.5);
        colors.push(color.r, color.g, color.b);
    }

    geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
    geometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));

    // Material - Increased size and opacity for better visibility
    const material = new THREE.PointsMaterial({
        size: 35, // Increased from 20 to 35 for visibility
        vertexColors: true,
        map: createCircleTexture(),
        transparent: true,
        opacity: 1.0, // Increased to max
        blending: THREE.AdditiveBlending,
        depthWrite: false
    });

    particles = new THREE.Points(geometry, material);
    scene.add(particles);

    // Renderer
    renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    container.appendChild(renderer.domElement);

    // Events
    document.addEventListener('mousemove', onDocumentMouseMove);
    window.addEventListener('resize', onWindowResize);
    
    // Check for theme changes
    const themeObserver = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.attributeName === "class") {
                updateThemeColors();
            }
        });
    });
    
    themeObserver.observe(document.body, {
        attributes: true
    });
    
    updateThemeColors(); // Initial check
}

function createCircleTexture() {
    const canvas = document.createElement('canvas');
    canvas.width = 32;
    canvas.height = 32;
    const context = canvas.getContext('2d');
    const center = 16;
    const radius = 16;

    const gradient = context.createRadialGradient(center, center, 0, center, center, radius);
    gradient.addColorStop(0, 'rgba(255,255,255,1)');
    gradient.addColorStop(1, 'rgba(255,255,255,0)');

    context.fillStyle = gradient;
    context.fillRect(0, 0, 32, 32);

    const texture = new THREE.Texture(canvas);
    texture.needsUpdate = true;
    return texture;
}

function updateThemeColors() {
    const isDark = document.body.classList.contains('dark-theme');
    const colors = particles.geometry.attributes.color.array;
    const color = new THREE.Color();
    
    // Update fog and material blending
    if (isDark) {
        scene.fog.color.setHex(0x1a1a1a);
        particles.material.blending = THREE.AdditiveBlending;
        particles.material.opacity = 0.9;
    } else {
        scene.fog.color.setHex(0xf0f2f5); // Slightly off-white for better visibility
        particles.material.blending = THREE.NormalBlending; // Normal blending for light background
        particles.material.opacity = 1.0;
    }
    particles.material.needsUpdate = true;
    
    // Update particle colors
    for (let i = 0; i < colors.length; i += 3) {
        if (isDark) {
            // Dark theme: Blue/Purple, light and bright
            color.setHSL(0.6 + Math.random() * 0.1, 0.8, 0.6); 
        } else {
            // Light theme: Darker Blue/Purple for visibility on light background
            color.setHSL(0.6 + Math.random() * 0.1, 0.8, 0.3);
        }
        
        colors[i] = color.r;
        colors[i + 1] = color.g;
        colors[i + 2] = color.b;
    }
    particles.geometry.attributes.color.needsUpdate = true;
}

function onWindowResize() {
    windowHalfX = window.innerWidth / 2;
    windowHalfY = window.innerHeight / 2;

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize(window.innerWidth, window.innerHeight);
}

function onDocumentMouseMove(event) {
    mouseX = (event.clientX - windowHalfX) * 0.5;
    mouseY = (event.clientY - windowHalfY) * 0.5;
}

function animate() {
    requestAnimationFrame(animate);
    render();
}

function render() {
    const time = Date.now() * 0.00005;

    camera.position.x += (mouseX - camera.position.x) * 0.05;
    camera.position.y += (-mouseY - camera.position.y) * 0.05;
    camera.lookAt(scene.position);

    // Rotate the particle system slowly
    particles.rotation.y = time * 2;
    particles.rotation.z = time * 1;

    // Pulse effect
    const sizes = particles.material.size;
    // particles.material.size = 15 + Math.sin(time * 10) * 5;

    renderer.render(scene, camera);
}
